package cn.kimming.generator;

import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.text.MessageFormat;

import cn.kimming.wms.domain.Client;
import cn.kimming.wms.util.XmlUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class CodeGenerator {
	
	private static Configuration cfg;
	
	 static {
		 cfg = new Configuration();
		 try {
			 cfg.setDirectoryForTemplateLoading(new File("templates"));
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
	 }
	
	public static void main(String[] args) throws Exception {
//		generate(XX.class, "X");
	}
	
	public static void generate(Class<?> clz, String entityName) throws Exception {
		ClassInfo classInfo = new ClassInfo(clz, entityName);
		//生成映射文件
		createTarget(classInfo, "hbm.xml", "src/main/resources/{0}/domain/{1}.hbm.xml");
		//生成DAO
		createTarget(classInfo, "IDAO.java", "src/main/java/{0}/dao/I{1}DAO.java");
		createTarget(classInfo, "DAOImpl.java", "src/main/java/{0}/dao/impl/{1}DAOImpl.java");
		//生成Service
		createTarget(classInfo, "IService.java", "src/main/java/{0}/service/I{1}Service.java");
		createTarget(classInfo, "ServiceImpl.java", "src/main/java/{0}/service/impl/{1}ServiceImpl.java");
		//生成Action
		createTarget(classInfo, "Action.java", "src/main/java/{0}/web/action/{1}Action.java");
		//生成前端页面
		createTarget(classInfo, "list.jsp", "src/main/webapp/WEB-INF/views/{2}/list.jsp");
		createTarget(classInfo, "input.jsp", "src/main/webapp/WEB-INF/views/{2}/input.jsp");
		createTarget(classInfo, "obj.js", "src/main/webapp/js/common/{2}.js");
		
		System.out.println("代码生成完成!");
	}
	
	public static void createTarget(ClassInfo classInfo, String templateFile, String target) throws Exception {
		Template template = cfg.getTemplate(templateFile);
		target = MessageFormat.format(target, classInfo.getBasePkg().replace(".", "/"),classInfo.getClassName(),classInfo.getObjectName());
		File targetFile = new File(target);
		if (!targetFile.getParentFile().exists()) {
			targetFile.getParentFile().mkdirs();
		}
		template.process(classInfo, new FileWriter(targetFile));
	}
	
	public static void appendTarget(ClassInfo classInfo, String templateFile, String target) throws Exception {
		Template template = cfg.getTemplate(templateFile);
		target = MessageFormat.format(target, classInfo.getBasePkg().replace(".", "/"),classInfo.getClassName(),classInfo.getObjectName());
		File targetFile = new File(target);
		if (!targetFile.getParentFile().exists()) {
			targetFile.getParentFile().mkdirs();
		}
		StringWriter appendingXml = new StringWriter();
		template.process(classInfo, appendingXml);
		XmlUtil.mergeXML(targetFile, appendingXml.toString());
	}
}
